load ../../Data/other/pwt9_rgdpftp.mat
% 
 ISO = string(pwt9rgdptfp.ISO);
 year_pwt = pwt9rgdptfp.year;
% rgdpe = pwt9rgdptfp.rgdpe;
 rgdpo = pwt9rgdptfp.rgdpo;
% rgdpna = pwt9rgdptfp.rgdpna;
 ctfp = pwt9rgdptfp.ctfp;
 cwtfp = pwt9rgdptfp.cwtfp;
% xr = pwt9rgdptfp.xr;
 
id = grp2idx(ISO);

% TFP is expressed in relative terms with respect to the US
% Express it in relative terms with respect to FRA
ctfp_france = ctfp(ISO=="FRA");
for i = 1:max(id)
    ctfp(id==i) = ctfp(id==i)./ctfp_france;
end

% Compute growth rate of TFP by country
for i = 1:max(id)
   
   x = ctfp(id==i);
   y = rgdpo(id==i);   
   grx = NaN(size(x,1),1);
   grx(2:end) = x(2:end)./x(1:end-1)-1;
   gdp = NaN(size(x,1),1);
   gdp(2:end) = y(1:end-1);   
   gr_ctfp(id==i) = grx;   
   w_rgdpo(id==i) = gdp; 
   
   clear x grx y gdp;
end

% Aggregate acorss countries
T = size(ctfp,1)/max(id);
WorldTFP_growth=zeros(1,T);
gr_ctfp_row=gr_ctfp;
gr_ctfp_row_matrix=zeros(max(id),T);
w_rgdpo_matrix=zeros(max(id),T);
for i=1:max(id)
    gr_ctfp_row_matrix(i,:) = gr_ctfp_row(1,(i-1)*T+1:i*T);
    w_rgdpo_matrix(i,:)  = w_rgdpo(1,(i-1)*T+1:i*T);
end
gr_ctfp_row_matrix(isnan(gr_ctfp_row_matrix)==1)=0;
w_rgdpo_matrix(isnan(w_rgdpo_matrix)==1)=0;
WorldTFP_growth = sum(gr_ctfp_row_matrix.*w_rgdpo_matrix,1)./sum(w_rgdpo_matrix,1);
for i=min(year_pwt):max(year_pwt)
    year(1,i-min(year_pwt)+1)=i;
end

% Aggregate across WIOT countries
CTY = {'AUS', 'AUT', 'BEL', 'BGR', 'BRA', 'CAN', 'CHN' ,'CYP', ...
'CZE', 'DEU', 'DNK', 'ESP' , 'EST', 'FIN', 'FRA', 'GBR', ...
'GRC', 'HUN', 'IDN', 'IND', 'IRL', 'ITA', 'JPN', 'KOR', ...
'LTU' ,'LVA', 'MEX','MLT', 'NLD', 'POL', 'PRT', 'ROU','RUS', ...
'SVK', 'SVN', 'SWE', 'TUR', 'TWN', 'USA','ROW'};
% Initialize vectors we will collect results in

% For all countries but ROW, keep PWT data
TFP_growth=zeros(size(CTY,2)-1,T);
w_rgdpo_all=zeros(size(CTY,2)-1,T);
gr_ctfp_row=gr_ctfp;
for i = 1:size(CTY,2)-1
    cty = string(CTY(i));
    growth =  gr_ctfp(ISO==cty);
    gdp =  w_rgdpo(ISO==cty);
    gr_ctfp_row(ISO==cty)=0;
    w_rgdpo(ISO==cty)=0;
    for t = 1:T
        TFP_growth(i,t)=growth(1,t);
        w_rgdpo_all(i,t)=gdp(1,t);
   end
end
TFP_growth(isnan(TFP_growth)==1)=0;
w_rgdpo_all(isnan(w_rgdpo_all)==1)=0;
AllTFP_growth = sum(TFP_growth.*w_rgdpo_all,1)./sum(w_rgdpo_all,1);

% Export as csv
 sol=[year' WorldTFP_growth' AllTFP_growth'];
 dlmwrite(strcat ('../../Data/other/WorldTFPGrowth.csv'),sol,'delimiter', ',', 'precision', '%12.9f');

